﻿using glb;
using PIMS.DBModel;
using PIMS.ORM;
using PIMS.Utils;
using PIMS.XmlModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace PIMS
{
    public partial class FormLogHistory : DockContent
    {
        public FormLogHistory()
        {
            InitializeComponent();
        }

        private void FormHistory_Load(object sender, EventArgs e)
        {
            if (Common.pimsConfig.GetAppValueByKey("english") == "1")
            { 
                label2.Text = "Key word";
                label18.Text = "Time range"; //起始时间
                cbTime.Text = "Time range";  //时间范围查询
                cbOrder.Text = "Descending"; //降序查询
                this.buttonQuery.Text = "Query"; //历史工单记录查询
               // this.btn_LoadFile.Text = "Loading log files"; //载入日志文件
            }

            // this.dateTimeStart.MinDate = DateTime.Now.AddDays(-365);
            this.dateTimeStart.Value = DateTime.Now.AddDays(-1);
            this.dateTimeEnd.Value = DateTime.Now;


            dataGridView(this.dataGridViewSql);
            this.dataGridViewSql.AutoGenerateColumns = false; //锁定列名

            //时间显示格式,默认的缺秒
            this.dataGridViewSql.Columns[4].DefaultCellStyle.Format = "yyyy/MM/dd HH:mm:ss";

            //日志分组查询
            cbFlag1.Visible= false;
            cbFlag2.Visible = false;
            cbFlag3.Visible = false;
            cbFlag4.Visible = false;
            cbFlag5.Visible = false;

            string[] plcGroup = new string[] { "weight", "packer", "pal", "label", "other" };
            for (int i = 0; i < plcGroup.Length; i++)
            {
                XPLC x = Common.pimsConfig.GetXPLCByKey(plcGroup[i]);
                switch (plcGroup[i])
                {
                    case "weight":                        
                        if (x.count > 0)
                        {
                            RadioButton cb = GetCheckBox();
                            cb.Visible = true;
                            if (!String.IsNullOrEmpty(x.methodName)) cb.Text = x.methodName;
                            cb.Tag = "weight";
                        }                           
                        break;
                    case "packer":
                        if (x.count > 0)
                        {
                            RadioButton cb = GetCheckBox();
                            cb.Visible = true;
                            if (!String.IsNullOrEmpty(x.methodName)) cb.Text = x.methodName;
                            cb.Tag = "packer";
                        }
                        break;
                    case "pal":
                        if (x.count > 0)
                        {
                            RadioButton cb = GetCheckBox();
                            cb.Visible = true;
                            if (!String.IsNullOrEmpty(x.methodName)) cb.Text = x.methodName;
                            cb.Tag = "pal";
                        }
                        break;
                    case "label":
                        if (x.count > 0)
                        {
                            RadioButton cb = GetCheckBox();
                            cb.Visible = true;
                            if (!String.IsNullOrEmpty(x.methodName)) cb.Text = x.methodName;
                            cb.Tag = "label";
                        }
                        break;
                    case "other":
                        if (x.count > 0)
                        {
                            RadioButton cb = GetCheckBox();
                            cb.Visible = true;
                            if (!String.IsNullOrEmpty(x.methodName)) cb.Text = x.methodName;
                            cb.Tag = "other";
                        }
                        break;
                }
            }
        }

        private RadioButton GetCheckBox()
        {
            if (!this.cbFlag1.Visible)
            {
                return this.cbFlag1;
            }
            if (!this.cbFlag2.Visible)
            {
                return this.cbFlag2;
            }
            if (!this.cbFlag3.Visible)
            {
                return this.cbFlag3;
            }
            if (!this.cbFlag4.Visible)
            {
                return this.cbFlag4;
            }
            if (!this.cbFlag5.Visible)
            {
                return this.cbFlag5;
            }
            return null;
        }

        private void buttonQuery_Click(object sender, EventArgs e)
        {
            try
            {
                this.buttonQuery.Enabled = false;              
                string brance = " and 1=1";
                //LogLevel
                if(cbError.Checked && !cbInfo.Checked)
                {
                    brance = " and LogLevel='Error'";
                }
                else if(!cbError.Checked && cbInfo.Checked)
                {
                    brance = " and LogLevel='Info'";
                }
                //LogGroup
                if(!this.cbAll.Checked)
                {
                    string group = " and 1=1";
                    if (this.cbFlag1.Checked)
                    {
                        group = $" and LogGroup ='{Common.logGroupName[this.cbFlag1.Tag.ToString()]}'";
                    }
                    if (this.cbFlag2.Checked)
                    {
                        group = $" and LogGroup ='{Common.logGroupName[this.cbFlag2.Tag.ToString()]}'";
                    }
                    if (this.cbFlag3.Checked)
                    {
                        group = $" and LogGroup ='{Common.logGroupName[this.cbFlag3.Tag.ToString()]}'";
                    }
                    if (this.cbFlag4.Checked)
                    {
                        group = $" and LogGroup ='{Common.logGroupName[this.cbFlag4.Tag.ToString()]}'";
                    }
                    if (this.cbFlag5.Checked)
                    {
                        group = $" and LogGroup ='{Common.logGroupName[this.cbFlag5.Tag.ToString()]}'";
                    }
                    brance += group;
                }

                if(numericUpDown1.Value>0)
                {
                    brance += $" and plcIndex = '{numericUpDown1.Value.ToString()}'";
                }
                string timeStart = dateTimeStart.Value.ToString("yyyy-MM-dd HH:mm:ss");
                string timeEnd = dateTimeEnd.Value.ToString("yyyy-MM-dd HH:mm:ss");
                if (!String.IsNullOrEmpty(this.关键字.Text))
                {
                    brance += " and LogMessage like '%" + this.关键字.Text + "%'";
                }
                string cmdSql = "";
                if (cbTime.Checked)
                {
                    cmdSql = string.Concat(new string[]
                    {
                      "select * from DBLog ",
                      " where LogDate between '" + timeStart + "' and '" + timeEnd + "'",
                      " ",
                      brance
                    });
                }
                else
                {
                    cmdSql = string.Concat(new string[]
                   {
                      "select * from DBLog ",
                      " where 1=1",
                      " ",
                      brance
                   });
                }
                if (this.cbOrder.Checked)
                {
                    cmdSql += " order by id desc";
                }

                DataTable dt = SQLiteDBHelper.Query(cmdSql);
                this.dataGridViewSql.DataSource = dt;
                DgvTools.dataGridViewAutoSize(this.dataGridViewSql);
                DgvTools.dataGridViewDisableSort(this.dataGridViewSql);
                MessageBox.Show("查询完毕！", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace, "Err", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // NetLog.CreateLog(ex);
            }
            this.buttonQuery.Enabled = true;
        }

        private void FormHistory_Enter(object sender, EventArgs e)
        {
            this.dateTimeStart.Value = DateTime.Now.AddDays(-1);
            this.dateTimeEnd.Value = DateTime.Now;
        }

        private void cbTime_CheckedChanged(object sender, EventArgs e)
        {
            if (cbTime.Checked)
            {
                this.dateTimeStart.Enabled = true;
                this.dateTimeEnd.Enabled = true;
            }
            else
            {
                this.dateTimeStart.Enabled = false;
                this.dateTimeEnd.Enabled = false;
            }
        }

        public static void dataGridView(DataGridView dataGridView)
        {
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            dataGridView.AllowUserToAddRows = false;
            dataGridView.AllowUserToDeleteRows = false;
            dataGridViewCellStyle1.BackColor = System.Drawing.Color.LightCyan;
            //  dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridView.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
            //所有单元格居中
            //  dataGridView.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            dataGridView.BackgroundColor = System.Drawing.Color.White;
            dataGridView.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            dataGridView.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
            //   dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;//211, 223, 240
            dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(211)))), ((int)(((byte)(223)))), ((int)(((byte)(240)))));
            dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            dataGridViewCellStyle2.ForeColor = System.Drawing.Color.Navy;
            dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridView.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;

            dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            dataGridView.EnableHeadersVisualStyles = false;
            dataGridView.GridColor = System.Drawing.SystemColors.GradientInactiveCaption;
            dataGridView.ReadOnly = true;
            dataGridView.RowHeadersVisible = false;
            dataGridView.RowTemplate.Height = 23;
            dataGridView.RowTemplate.ReadOnly = true;
            //dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            dataGridView.AllowUserToOrderColumns = false;
            dataGridView.AllowUserToResizeRows = false;
            dataGridView.AllowDrop = false;
        }

        private void cbAll_CheckedChanged(object sender, EventArgs e)
        {
            if(this.cbAll.Checked)
            {
                this.cbFlag1.Checked = false;
                this.cbFlag2.Checked = false;
                this.cbFlag3.Checked = false;
                this.cbFlag4.Checked = false;
                this.cbFlag5.Checked = false;
                this.numericUpDown1.Value= 0;
            }
        }

        private void cbFlag1_CheckedChanged(object sender, EventArgs e)
        {
            if(this.cbFlag1.Checked)
            {
                this.cbAll.Checked = false;
            }
        }

        private void cbFlag2_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbFlag2.Checked)
            {
                this.cbAll.Checked = false;
            }
        }

        private void cbFlag3_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbFlag3.Checked)
            {
                this.cbAll.Checked = false;
            }
        }

        private void cbFlag4_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbFlag4.Checked)
            {
                this.cbAll.Checked = false;
            }
        }

        private void cbFlag5_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbFlag5.Checked)
            {
                this.cbAll.Checked = false;
            }
        }


    }
}
